/***************************************************************************
 *   Copyright (C) 2007 by Warren Kenny   				   *
 *   warren.kenny@gmail.com   						   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <gsNet/gsSocket.h>

gsSocket::gsSocket() :
m_socketHandle( GS_NULL )
{
}

gsSocket::gsSocket( gsInt handle ) :
m_socketHandle( handle )
{
}

gsBool gsSocket::establishConnection( gsAddress remoteHost )
{
	if( m_socketHandle )
	{
		breakConnection();
	}
	
	m_socketHandle = socket(AF_INET, SOCK_STREAM, 0);
	
	if( m_socketHandle != -1 )
	{
		struct sockaddr_in socketAddress;
		
		socketAddress.sin_family = AF_INET;
		socketAddress.sin_port = remoteHost.getPort();
		socketAddress.sin_addr.s_addr = remoteHost.getAddress();
		
		return ( connect( m_socketHandle, 
			 	  reinterpret_cast<struct sockaddr *>(&socketAddress), 
				  sizeof( socketAddress ) ) == 0 );	
	}
	else
	{
		return false;
	}
}
	
const gsInt gsSocket::receiveData( void *dataBuffer, const gsUInt32 bufferSize )
{
	return recv( m_socketHandle, dataBuffer, bufferSize, 0 );
}
	 
const gsInt gsSocket::sendData( const void *dataBuffer, const gsUInt32 bufferSize )
{
	return send( m_socketHandle, dataBuffer, bufferSize, 0 );
}

void gsSocket::breakConnection()
{
	shutdown( m_socketHandle, SHUT_RDWR );
}

gsInt gsSocket::getSocketHandle() const
{
	return m_socketHandle;
}

gsSocket::~gsSocket()
{
	breakConnection();
}


